package com.definity.toolkit.email;

import java.util.ArrayList;
import java.util.List;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.definity.toolkit.service.ServiceException;

@Service
public class EmailServiceImpl implements EmailService {

	private static final Logger logger = Logger.getLogger(EmailServiceImpl.class);

	@Autowired(required=false)
	private Session mailSession;
	
	public EmailServiceImpl() {

	}

	public void send(Email email) throws ServiceException {
		Session session = mailSession;
		session.setDebug(true);

		MimeMessage message = new MimeMessage(session);

		try {
			List<InternetAddress> addresses = new ArrayList<InternetAddress>();

			for (String recipient : email.getTo()) {
				logger.debug("Adding recipient " + recipient);

				try {
					InternetAddress addr = new InternetAddress(recipient);
					addr.validate();
					addresses.add(addr);
				} catch (Exception ae) {
					throw new EmailException("invalid.email", ae);
				}
			}

			if (addresses.size() <= 0) {
				throw new EmailException("no.recipient");
			}

			InternetAddress[] addressList = new InternetAddress[addresses.size()];
			addresses.toArray(addressList);

			message.setRecipients(Message.RecipientType.TO, addressList);
			message.setFrom(new InternetAddress(email.getFrom()));
			message.setSubject(email.getSubject(), "utf-8");

			MimeBodyPart body = new MimeBodyPart();
			body.setContent(email.getContent(), email.getContentType());

			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(body);

			if (!email.getAttachments().isEmpty()) {
				for (Attachment attachment : email.getAttachments()) {
					MimeBodyPart bodyAttachment = new MimeBodyPart();

					ByteArrayDataSource bads = new ByteArrayDataSource(attachment.getFileData(), attachment.getMimeType());

					bodyAttachment.setDataHandler(new DataHandler(bads));
					bodyAttachment.setFileName(attachment.getFileName());

					multipart.addBodyPart(bodyAttachment);
				}
			}

			message.setContent(multipart);
		} catch (Exception e) {
			logger.error("Error adding email part", e);
			throw new EmailException("send", e);
		}

		try {
			Transport.send(message, message.getAllRecipients());
		} catch (Exception e) {
			logger.error("Email Service", e);
			throw new EmailException("send", e);
		}

	}

}
